<?php
/**
 * 系统设置
 * User: dxk
 * Date: 2018/11/10
 */
namespace App\Model\Core\Sys;

use App\Model\CoreModel;
use App\Service\ParamsService;

class SysConfigModel extends CoreModel
{
    protected string $table = 'sys_config';

    /**
     * 获取配置
     * @param string $config_item
     * @param bool $is_cache
     * @return array
     */
    public function getConfig(string $config_item, bool $is_cache = true): array
    {
        $config_item = trim($config_item);
        if (empty($config_item) || !array_key_exists($config_item, ParamsService::$config_item_list)) {
            return [];
        }
        return self::cache('config' . $config_item, function () use ($config_item) {
            $config_info = $this->getConnectionTable()->where('config_item', $config_item)->first();
            $config_info = obj_to_array($config_info);
            if (isset($config_info['config_val'])) {
                $config_val = json_decode($config_info['config_val'], true);
                if (empty($config_val)) {
                    $config_val = $config_info['config_val'];
                }
                $config_info['config_val'] = $config_val;
            }
            return $config_info;
        }, $is_cache);
    }

    /**
     * 设置配置
     * @param $config_item
     * @param $config_val
     * @param $updated_by
     * @return bool|int
     */
    public function setConfig($config_item, $config_val, $updated_by): bool|int
    {
        $config_item = trim($config_item);
        if (empty($config_item) || !array_key_exists($config_item, ParamsService::$config_item_list)) {
            return false;
        }
        $config_info = self::getConfig($config_item);
        if (md5(json_encode($config_info['config_val'], JSON_UNESCAPED_UNICODE)) === md5(json_encode($config_val, JSON_UNESCAPED_UNICODE))) {
            return true;
        }
        if (is_array($config_val)) {
            $config_val = json_encode($config_val, JSON_UNESCAPED_UNICODE);
        }
        $data = ['config_val' => $config_val, 'updated_by' => $updated_by, 'updated_at' => date('Y-m-d H:i:s')];
        if (empty($config_info)) {
            $data['config_item'] = $config_item;
            $data['config_name'] = ParamsService::$config_item_list[$config_item]['name'];
            $res = $this->getConnectionTable()->insert($data);
        } else {
            $res = $this->getConnectionTable()->where('config_item', $config_item)->update($data);
        }
        self::getConfig($config_item, false);
        return $res;
    }
}
